const useDictStore = defineStore(
  'dict',
  {
    state: () => ({
      dict: []
    }),
    actions: {
      // 通过字典的类别和名称获取值
      getDictMapping(type) {
        if (type == null && type === "") {
          return {};
        }

        const dict = this.getDict(type);
        console.log('dict, type', dict, type);
        if (!dict || !dict.length) {
          return {};
        }
        return dict.reduce((obj, item)=> {
          obj[item.value] = item.label;
          return obj;
        }, {});

      },
      getDictValue(type, key) {
        if (type == null && type === "") {
          return null;
        }
        if (key == null && key === "") {
          return null;
        }
        const dict = this.getDict(type);
        for (let i = 0; i < dict.length; i++) {
          const item = dict[i];
          if (item.value === key) {
            return item.label;
          }
        }
      },
      // 获取字典
      getDict(_key) {
        if (typeof _key !== 'number' && !_key) {
          return null;
        }
        try {
          for (let i = 0; i < this.dict.length; i++) {
            if (this.dict[i].key == _key) {
              return this.dict[i].value;
            }
          }
        } catch (e) {
          return null;
        }
      },
      // 设置字典
      setDict(_key, value) {

        if (_key !== null && _key !== "") {
          this.dict.push({
            key: _key,
            value: value
          });
        }
      },
      // 删除字典
      removeDict(_key) {
        var bln = false;
        try {
          for (let i = 0; i < this.dict.length; i++) {
            if (this.dict[i].key == _key) {
              this.dict.splice(i, 1);
              return true;
            }
          }
        } catch (e) {
          bln = false;
        }
        return bln;
      },
      // 清空字典
      cleanDict() {
        this.dict = new Array();
      },
      // 初始字典
      initDict() {
      }
    }
  })

export default useDictStore
